// Created by Joe on 2017/7/20.

/**
 * it's necessary to put this service before other service
 * that need access_token, because if not, request will fail
 */

app.service(
    'AccessTokenService',
    [
        'config', '$http', '$q', 'UserService',
        function (config, $http, $q, UserService) {
            return {
                getAccessToken: function () {
                    var deferred = $q.defer();
                    $http.post(config.UserServer + '/checkToken', {}, {
                        headers: {
                            build: config.Build,
                            version: config.Version,
                            cityCode: config.curCity.cityCode
                        },
                        params: {
                            jsonTokens: {
                                accessToken: 'accessToken',
                                deviceToken: config.deviceToken,
                                pushToken: 'android',
                                os: 'android',
                                model: 'emui',
                                osVersion: '7.0',
                                appVersion: '2.4.3',
                                type: 'on'
                            }
                        }
                    }).success(function (tokenInfo) {
                        if (tokenInfo.code === '0000') {
                            if (tokenInfo.result[0] && !UserService.accessToken) {
                                UserService.accessToken = tokenInfo.result[0].access_token;
                            }
                        } else {
                            console.log(tokenInfo);
                        }
                        deferred.resolve();
                    }).error(function (error) {
                        console.log(error);
                    });
                    return deferred.promise;
                }
            }
        }
    ]
);